package com.ia.aistream.manager.quartz.impl;

import com.ia.aistream.common.exception.base.BaseException;
import com.ia.aistream.common.exception.job.TaskException;
import com.ia.aistream.manager.quartz.ISysJobManager;
import com.ia.aistream.manager.quartz.util.QuartzDisallowConcurrentExecution;
import com.ia.aistream.manager.quartz.util.QuartzJobExecution;
import com.ia.aistream.mapper.quartz.SysJobMapper;
import com.ia.aistream.model.quartz.constant.SysJobConstants;
import com.ia.aistream.model.quartz.entity.SysJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * 定时任务调度信息 服务层
 *
 * @author ai
 */
@Service
public class SysJobManagerImpl implements ISysJobManager {
    @Autowired
    private Scheduler scheduler;
    @Autowired
    private SysJobMapper jobMapper;

    /**
     * 新增任务
     *
     * @param job 调度信息 调度信息
     */
    @Override
    public int insertJob(SysJob job) throws SchedulerException, TaskException {
        int jobCount = jobMapper.countCheckJob(null, job.getJobName(), job.getJobGroup());
        if (jobCount > 0) {
            throw new BaseException("任务名称已经存在");
        }
        job.setStatus(SysJobConstants.Status.PAUSE.getValue());
        int rows = jobMapper.insert(job);
        if (rows > 0) {
            createScheduleJob(job);
        }
        return rows;
    }

    /**
     * 更新任务的时间表达式
     *
     * @param job 调度信息
     */
    @Override
    public int updateJob(SysJob job) throws SchedulerException, TaskException {
        int jobCount = jobMapper.countCheckJob(job.getJobId(), job.getJobName(), job.getJobGroup());
        if (jobCount > 0) {
            throw new BaseException("任务名称已经存在");
        }

        SysJob properties = jobMapper.selectById(job.getJobId());
        int rows = jobMapper.updateById(job);
        if (rows > 0) {
            job.setStatus(properties.getStatus());
            updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    /**
     * 删除任务后，所对应的trigger也将被删除
     *
     * @param job 调度信息
     */
    @Override
    public int deleteJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = jobMapper.deleteById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 批量删除调度信息
     *
     * @param jobIds 需要删除的任务ID
     * @return 结果
     */
    @Override
    public void deleteJobByIds(List<Long> jobIds) throws SchedulerException {
        for (Long jobId : jobIds) {
            SysJob job = jobMapper.selectById(jobId);
            deleteJob(job);
        }
    }

    /**
     * 暂停任务
     *
     * @param job 调度信息
     */
    @Override
    public int pauseJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(SysJobConstants.Status.PAUSE.getValue());
        int rows = jobMapper.updateById(job);
        if (rows > 0) {
            scheduler.pauseJob(getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 恢复任务
     *
     * @param job 调度信息
     */
    @Override
    public int resumeJob(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(SysJobConstants.Status.NORMAL.getValue());
        int rows = jobMapper.updateById(job);
        if (rows > 0) {
            scheduler.resumeJob(getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    /**
     * 任务调度状态修改
     *
     * @param job 调度信息
     */
    @Override
    public int changeStatus(SysJob job) throws SchedulerException {
        int rows = 0;
        String status = job.getStatus();
        if (SysJobConstants.Status.NORMAL.getValue().equals(status)) {
            rows = resumeJob(job);
        } else if (SysJobConstants.Status.PAUSE.getValue().equals(status)) {
            rows = pauseJob(job);
        }
        return rows;
    }

    /**
     * 立即运行任务
     *
     * @param job 调度信息
     */
    @Override
    public void run(SysJob job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        SysJob properties = jobMapper.selectById(job.getJobId());
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(SysJobConstants.TASK_PROPERTIES, properties);
        scheduler.triggerJob(getJobKey(jobId, jobGroup), dataMap);
    }

    /**
     * 校验cron表达式是否有效
     *
     * @param cronExpression 表达式
     * @return 结果
     */
    @Override
    public boolean checkCronExpression(String cronExpression) {
        return CronExpression.isValidExpression(cronExpression);
    }

    @Override
    public Date getNextExecution(String expression, Date beginTime) {
        try {
            CronExpression cron = new CronExpression(expression);
            return cron.getNextValidTimeAfter(beginTime);
        } catch (ParseException e) {
            throw new IllegalArgumentException(e.getMessage());
        }
    }

    private void createScheduleJob(SysJob job) throws TaskException, SchedulerException {
        Class<? extends Job> jobClass = getQuartzJobClass(job);
        // 构建job信息
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(getJobKey(jobId, jobGroup)).build();

        // 表达式调度构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression());
        cronScheduleBuilder = handleCronScheduleMisfirePolicy(job, cronScheduleBuilder);

        // 按新的cronExpression表达式构建一个新的trigger
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId, jobGroup))
                .withSchedule(cronScheduleBuilder).build();

        // 放入参数，运行时的方法可以获取
        jobDetail.getJobDataMap().put(SysJobConstants.TASK_PROPERTIES, job);

        // 判断是否存在
        if (scheduler.checkExists(getJobKey(jobId, jobGroup))) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(getJobKey(jobId, jobGroup));
        }

        scheduler.scheduleJob(jobDetail, trigger);

        // 暂停任务
        if (job.getStatus().equals(SysJobConstants.Status.PAUSE.getValue())) {
            scheduler.pauseJob(getJobKey(jobId, jobGroup));
        }
    }

    /**
     * 更新任务
     *
     * @param job      任务对象
     * @param jobGroup 任务组名
     */
    public void updateSchedulerJob(SysJob job, String jobGroup) throws SchedulerException, TaskException {

        Long jobId = job.getJobId();
        // 判断是否存在
        JobKey jobKey = getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        createScheduleJob(job);
    }

    /**
     * 得到quartz任务类
     *
     * @param sysJob 执行计划
     * @return 具体执行任务类
     */
    private Class<? extends Job> getQuartzJobClass(SysJob sysJob) {
        boolean isConcurrent = "0".equals(sysJob.getConcurrent());
        return isConcurrent ? QuartzJobExecution.class : QuartzDisallowConcurrentExecution.class;
    }

    /**
     * 构建任务键对象
     */
    private JobKey getJobKey(Long jobId, String jobGroup) {
        return JobKey.jobKey(SysJobConstants.TASK_CLASS_NAME + jobId, jobGroup);
    }

    /**
     * 构建任务触发对象
     */
    private TriggerKey getTriggerKey(Long jobId, String jobGroup) {
        return TriggerKey.triggerKey(SysJobConstants.TASK_CLASS_NAME + jobId, jobGroup);
    }

    /**
     * 设置定时任务策略
     */
    private CronScheduleBuilder handleCronScheduleMisfirePolicy(SysJob job, CronScheduleBuilder cb)
            throws TaskException {
        switch (job.getMisfirePolicy()) {
            case SysJobConstants.MISFIRE_DEFAULT:
                return cb;
            case SysJobConstants.MISFIRE_IGNORE_MISFIRES:
                return cb.withMisfireHandlingInstructionIgnoreMisfires();
            case SysJobConstants.MISFIRE_FIRE_AND_PROCEED:
                return cb.withMisfireHandlingInstructionFireAndProceed();
            case SysJobConstants.MISFIRE_DO_NOTHING:
                return cb.withMisfireHandlingInstructionDoNothing();
            default:
                throw new TaskException("The task misfire policy '" + job.getMisfirePolicy()
                        + "' cannot be used in cron schedule tasks", TaskException.Code.CONFIG_ERROR);
        }
    }
}